package com.liaoye;

import java.util.ArrayList;
import java.util.List;

public class AppleTest {
    public static void main(String[] args) {

        List<Apple> list = new ArrayList<>();
        list.add(new Apple("red", 100));
        list.add(new Apple("green", 100));
        list.add(new Apple("red", 150));
        list.add(new Apple("green", 150));
        list.add(new Apple("red", 200));
        list.add(new Apple("green", 200));
        list.add(new Apple("green", 200));
        System.out.println(list);

        //需求过滤红色的苹果
        List<Apple> redAppleList = filterApples(list, new AppleRedPredicate());
        System.out.println("红色的苹果为: " + redAppleList);

        //需求重量超过150的苹果
        List<Apple> heavyAppleList = filterApples(list, new AppleHeavyPredicate());
        System.out.println("重量超过150的苹果为: " + heavyAppleList);

        prettyPrintApples(list, new AppleFancyFormatter());

        //使用匿名类 过滤红色且重量超过150的苹果
        List<Apple> appleList = filterApples(list, new ApplePredicate() {
            @Override
            public boolean test(Apple apple) {
                return apple.getColor().equals("red") && apple.getWeight() > 150;
            }
        });
        System.out.println("红色且重量超过150的苹果为: " + appleList);

        //使用lambda 过滤红色的苹果
        List<Apple> aList = filterApples(list, (Apple apple) -> "red".equals(apple.getColor()));
        System.out.println("红色的苹果2为: " + aList);


        System.out.println(String.valueOf(formatValue(1.86)));
        System.out.println(String.valueOf(formatValue(1.85)));
        System.out.println(String.valueOf(formatValue(0.86)));
        System.out.println(String.valueOf(formatValue(0.85)));
    }

    //行为参数化
    public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) {
        List<Apple> resultList = new ArrayList<>();
        for (Apple apple : inventory) {
            if (p.test(apple)) {
                resultList.add(apple);
            }
        }
        return resultList;
    }

    public static void prettyPrintApples(List<Apple> apples, AppleFormatter f) {
        for (Apple apple : apples) {
            String s = f.accept(apple);
            System.out.println(s);
        }
    }


    public static double formatValue(double value) {
        if (value <= 1) {
            double tempVal = value - (int) value;
            if (tempVal > 0.85) {
                return Math.ceil(value);
            } else {
                return Math.floor(value);
            }
        } else {
            double tempVal = value - (int) value;
            if (tempVal > 0.86) {
                return Math.ceil(value);
            } else {
                return Math.floor(value);
            }
        }
    }

}
